package com.zhongshengnetwork.rightbe.wzt.view;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
//import android.support.annotation.NonNull;
//import android.support.annotation.Nullable;
//import android.support.v4.content.ContextCompat;
//import android.support.v4.widget.NestedScrollView;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.activity.ReportActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.customview.PublishSelectPicPopupWindow;
import com.zhongshengnetwork.rightbe.common.expandabletextview.ExpandableTextView;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.DateModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuContentDetailModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.SelfImagePreviewActivity;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.lang.res.Configs;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTContentActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTContentPublishActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTContentSearchActivity;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.content.Context.CLIPBOARD_SERVICE;

public class WZTContentFragment extends BaseAnalyticsFragment {

    private long id;
    private String wztUserId = "";
    private Byte contentType = 0;
    private boolean canBrowseAll = false;
    private boolean needCare = false;
    private boolean careState = false;
    private boolean canPublish = false;
    private String title = "";

    private int pageindex = 0;
    private static final int Records = 20;
    private static final int maxReadCount = 10;
    //private String lastDay = "";
    private boolean isHasMore = false;
    private List<WeiShuContentDetailModel> list;
    private RecyclerView listview;
    //private WZTContentAdapter wztContentAdapter;
    private WZTRecyclerAdapter wztRecyclerAdapter;
    private View rootView;//缓存Fragment view
    private int imgW = 0;

    //加载动画
    private AVLoadingIndicatorView avi;
    private RefreshLayout mRefreshLayout;
    //private NestedScrollView wzt_nestedScrollView_layout;

    private ClipboardManager myClipboard;

    private Button publish_button;
    private ImageView no_data_img;

    private int screenWidth = 0;
    private float density = 0;

    private TextView wzt_load_all;
    private ImageView publish_img;

    private RelativeLayout search_top;

    private MyListener myListener;//②作为属性定义
    //①定义回调接口
    public interface MyListener{
        public void publishSend();
        public void contentLoaded();
        public void goContentDetail();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        myListener = (MyListener) getActivity();
    }

    public static WZTContentFragment newInstance(long id, String userid, Byte contentType, boolean canBrowseAll, boolean needCare, boolean careState, boolean canPublish, String title){
        WZTContentFragment wztContentFragment = new WZTContentFragment();
        Bundle bundle = new Bundle();
        bundle.putLong("id",id);
        bundle.putString("userid",userid);
        bundle.putByte("contentType", contentType);
        bundle.putBoolean("canBrowseAll", canBrowseAll);
        bundle.putBoolean("needCare", needCare);
        bundle.putBoolean("careState", careState);
        bundle.putBoolean("canPublish",canPublish);
        bundle.putString("title", title);
        wztContentFragment.setArguments(bundle);
        //Log.e("TAG","id="+id+"  userid="+userid);
        //id=1851  userid=068602263309
        return wztContentFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null){
            id = args.getLong("id");
            wztUserId = args.getString("userid");
            contentType = args.getByte("contentType", Byte.valueOf("0"));
            canBrowseAll = args.getBoolean("canBrowseAll");
            needCare = args.getBoolean("needCare");
            careState = args.getBoolean("careState");
            canPublish = args.getBoolean("canPublish");
            title = args.getString("title");
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        calculateImageWidth();
    }

    private void calculateImageWidth(){
        screenWidth = ScreenUtils.getScreenWidth(getActivity());
        density = ScreenUtils.getScreenDensity(getActivity());
        if (contentType == 2){
            imgW = (int) ((screenWidth-130*density)/3);
        }else {
            imgW = (int) ((screenWidth-30*density)/3);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        calculateImageWidth();
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.wzt_content_viewpaper_layout, container, false);
            publish_button = (Button) rootView.findViewById(R.id.publish_button);
            publish_button.setBackgroundResource(AppThemeUtils.getInstance().getButtonBg());
            publish_button.setClickable(true);
            if (contentType == 2){
                publish_button.setText("写日记");
            }
            publish_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    myListener.publishSend();
                }
            });
            wzt_load_all = rootView.findViewById(R.id.wzt_load_all);
            wzt_load_all.setClickable(true);
            wzt_load_all.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showCare();
                }
            });
            no_data_img = (ImageView) rootView.findViewById(R.id.no_data_img);
            avi = (AVLoadingIndicatorView)rootView.findViewById(R.id.avi);
            publish_img = (ImageView) rootView.findViewById(R.id.publish_img);
            publish_img.setClickable(true);
            publish_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    myListener.publishSend();
                }
            });
            if (canPublish == true){
                publish_img.setVisibility(View.VISIBLE);
            }else {
                publish_img.setVisibility(View.GONE);
            }
            pageindex = 0;
            myClipboard = (ClipboardManager)getActivity().getSystemService(CLIPBOARD_SERVICE);
            if (list == null){
                list = new ArrayList<WeiShuContentDetailModel>();
            }

            listview=(RecyclerView) rootView.findViewById(R.id.wzt_listview);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
            listview.setLayoutManager(layoutManager);
            listview.setHasFixedSize(false);
            listview.setNestedScrollingEnabled(false);
            ((DefaultItemAnimator) listview.getItemAnimator()).setSupportsChangeAnimations(false);//解决局部更新闪烁问题
            wztRecyclerAdapter = new WZTRecyclerAdapter(list, getActivity(), listview, contentType, canBrowseAll, wztUserId, id);
            listview.setAdapter(wztRecyclerAdapter);

            mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(false);//禁用刷新
            mRefreshLayout.setEnableLoadMore(false);//启用加载
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    getData(false);
                }
            });

            LinearLayout wzt_content_layout = (LinearLayout) rootView.findViewById(R.id.wzt_content_layout);
            wzt_content_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

            search_top = (RelativeLayout) rootView.findViewById(R.id.search_top);
            search_top.setClickable(true);
            search_top.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), WZTContentSearchActivity.class);
                    intent.putExtra("id", id);
                    intent.putExtra("userid", wztUserId);
                    intent.putExtra("contentType", contentType);
                    intent.putExtra("canBrowseAll", canBrowseAll);
                    intent.putExtra("needCare", needCare);
                    intent.putExtra("careState", careState);
                    intent.putExtra("canPublish", canPublish);
                    intent.putExtra("title", title);
                    startActivity(intent);
                }
            });
            search_top.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            RelativeLayout search_shape_layout = (RelativeLayout) rootView.findViewById(R.id.search_shape_layout);
            search_shape_layout.setBackgroundResource(AppThemeUtils.getInstance().getSearchBackground());

            getData(true);
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }

        return rootView;
    }

    private void updateUI(){
        publish_button.setVisibility(View.INVISIBLE);
        no_data_img.setVisibility(View.INVISIBLE);
        if (list.size() == 0){
            if (CommonUtils.isLogin() == true && CustomApplication.loginModel.getUid().equals(wztUserId)){
                publish_button.setVisibility(View.VISIBLE);
            }else {
                no_data_img.setVisibility(View.VISIBLE);
            }
        }
    }

    private void showCare(){
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
        builder.setTitle("温馨提示");
        builder.setMessage("关注作者后才可以查看全部内容，是否现在添加关注？");
        builder.setPositiveButton("关注", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                addCare();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void addCare(){
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(getActivity(),LoginActivity.class);
            startActivity(intent);
            return;
        }
        if (careState == false){
            if (wztUserId.equals(CustomApplication.loginModel.getUid())){
                canBrowseAll = true;
                careState = true;
                wzt_load_all.setVisibility(View.GONE);
                wztRecyclerAdapter.canBrowseAll = true;
                wztRecyclerAdapter.notifyDataSetChanged();
                return;
            }
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("authorid", wztUserId);
            String url = "miniapp/"+"langappid"+"/addcare.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    if (getActivity() != null){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CommonModel commonModel = GsonTools.getCommonModel(data);
                                if (commonModel.getFlag().equals("1")){
                                    ToastUtil.show(getActivity(), "关注成功");
                                    canBrowseAll = true;
                                    careState = true;
                                    wzt_load_all.setVisibility(View.GONE);
                                    wztRecyclerAdapter.canBrowseAll = true;
                                    wztRecyclerAdapter.notifyDataSetChanged();
                                }else {
                                    ToastUtil.show(getActivity(), commonModel.getMsg());
                                }
                            }
                        });
                    }

                }

                @Override
                public void onError(String msg) {
                    if (getActivity() != null){
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.show(getActivity(), "添加关注失败");
                            }
                        });
                    }
                }
            });
        }else {
            canBrowseAll = true;
            careState = true;
            wzt_load_all.setVisibility(View.GONE);
            wztRecyclerAdapter.canBrowseAll = true;
            wztRecyclerAdapter.notifyDataSetChanged();
        }
    }

    public void getData(boolean isFirst){

        if (isFirst == true){
            pageindex = 0;
        }

        if (list != null && list.size() > maxReadCount && canBrowseAll == false){
            mRefreshLayout.finishLoadMore();
            showCare();
            return;
        }else {
            if (wzt_load_all.getVisibility() == View.VISIBLE){
                wzt_load_all.setVisibility(View.GONE);
            }
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                map.put("dataId",""+id);
                map.put("dataType", "0");
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                HttpsUtils.miniAppDo(map, "weishu/theme/list.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<WeiShuContentDetailModel> l = GsonTools.getWeiShuContentDetailModelList(data);
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        mRefreshLayout.finishLoadMore();
                                    }
                                    if (isFirst == true){
                                        myListener.contentLoaded();
                                    }
                                    int fromposition = list.size();
                                    if (l != null && l.size() > 0){
                                        if (l.size() >= Records){
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        if (pageindex == 0){
                                            list.clear();
                                        }
                                        list.addAll(l);
                                    }else {
                                        isHasMore = false;
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    if (pageindex == 0){
                                        wztRecyclerAdapter.notifyDataSetChanged();
                                    }else {
                                        wztRecyclerAdapter.notifyItemRangeChanged(fromposition, l.size());
                                    }
                                    if (l != null && l.size() > 0){
                                        pageindex += 1;
                                    }
                                    updateUI();
                                    if (list != null && list.size() > maxReadCount && canBrowseAll == false){
                                        if (wzt_load_all.getVisibility() == View.GONE){
                                            wzt_load_all.setVisibility(View.VISIBLE);
                                        }
                                    }

                                }
                            });
                        }else {
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRefreshLayout.finishLoadMore();
                                    if (isFirst == true){
                                        myListener.contentLoaded();
                                    }
                                    CustomApplication.showTip(commonModel, getActivity());
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        if (getActivity() == null){
                            return;
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (isFirst == true){
                                    myListener.contentLoaded();
                                }
                                mRefreshLayout.finishLoadMore();
                            }
                        });
                    }
                });
            }
        }).start();

    }


}
